package com.newdjk.newdoctor.ui;

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.bilibili.boxing.Boxing;
import com.bilibili.boxing.model.config.BoxingConfig;
import com.bilibili.boxing.model.entity.BaseMedia;
import com.google.gson.Gson;
import com.newdjk.newdoctor.BasActivity;
import com.newdjk.newdoctor.R;
import com.newdjk.newdoctor.dialog.LoadDialog;
import com.newdjk.newdoctor.entity.GroupChoosePersonData;
import com.newdjk.newdoctor.entity.SendGroupMessageEntity;
import com.newdjk.newdoctor.entity.UploadImageEntity;
import com.newdjk.newdoctor.net.BaseComPleteObserver;
import com.newdjk.newdoctor.net.NetServices;
import com.newdjk.newdoctor.utils.Base64Util;
import com.newdjk.newdoctor.utils.Contants;
import com.newdjk.newdoctor.utils.DisplayUtil;
import com.newdjk.newdoctor.utils.SpUtils;
import com.newdjk.newdoctor.utils.StrUtil;
import com.newdjk.newdoctor.utils.ToastUtil;
import com.newdjk.newdoctor.view.MultiImageUploadView;
import com.newdjk.newdoctor.view.RoundImageUploadView;
import com.newdjk.okhttp.entity.BaseEntity;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import top.zibin.luban.CompressionPredicate;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class NewlyBuildGroupActivity extends BasActivity {


    private static final String TAG = "NewlyBuildGroupActivity";
    @BindView(R.id.icon)
    ImageView icon;
    @BindView(R.id.mDate)
    TextView mDate;
    @BindView(R.id.mEditContent)
    EditText mEditContent;
    @BindView(R.id.upload_view)
    RoundImageUploadView uploadView;
    @BindView(R.id.icon_1)
    ImageView icon1;
    @BindView(R.id.textView)
    TextView textView;
    @BindView(R.id.icon_2)
    ImageView icon2;
    @BindView(R.id.mPersonContent)
    TextView mPersonContent;
    @BindView(R.id.mChoosePerson)
    RelativeLayout mChoosePerson;
    @BindView(R.id.mGroupBtn)
    TextView mGroupBtn;

    private String ids;
    private Gson mGson;
    private static final int IMG_REQUEST_CODE = 0x010;
    private ArrayList<String> mPicList = new ArrayList<>(); //上传的图片凭证的数据源
    private List<String> mSavePicList = new ArrayList<>(); //上传的图片凭证的数据源
    private final int IMAGE_REQUEST_CODE = 2;

    @Override
    public boolean IsShowBackIcon() {
        return true;
    }

    @Override
    protected String setTitle() {
        return "新建群发";
    }

    @Override
    protected int initViewResId() {
        return R.layout.activity_newly_build_group;
    }

    @Override
    protected void initView() {


        setUploadView();
    }

    private void setUploadView() {
        uploadView.setAddHandlerImage(R.drawable.icon_upload_pic);
        uploadView.setImageSizeConfig(new MultiImageUploadView.ImageSizeConfig() {
            @Override
            public int getWidth() {
                return 200;
            }

            @Override
            public int getHeight() {
                return 200;
            }
        });
        uploadView.setMax(9);
        uploadView.setNumCol(4);
        uploadView.setImgMargin(DisplayUtil.dp2px(this, 10));
        uploadView.setCloseHandlerImage(R.drawable.ic_delete_photo);
        uploadView.setOnImageChangeListener(new MultiImageUploadView.OnImageChangeListener() {
            @Override
            public void onImageChage(List<File> imgFiles, int maxSize) {

            }
        });
        uploadView.setPadding(0, 0, 0, 0);
        uploadView.setAddClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startSelectImage();
            }
        });

        uploadView.setOnDelPicListener(new MultiImageUploadView.OnDelPicListener() {
            @Override
            public void onDelPicListener(int pos) {
                mSavePicList.remove(pos);
            }
        });
    }


    private void startSelectImage() {
//        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//        startActivityForResult(intent, IMAGE_REQUEST_CODE);

        BoxingConfig mulitImgConfig = new BoxingConfig(BoxingConfig.Mode.SINGLE_IMG)
                .needCamera(R.drawable.ic_camera)
                .needGif()
                .withMaxCount(uploadView.getMax() - uploadView.getFiles().size());
        Boxing.of(mulitImgConfig).
                withIntent(this, MyBoxingActivity.class).
                start(this, IMAGE_REQUEST_CODE);


    }


    @Override
    protected void initListener() {

    }

    @Override
    protected void initData() {
        mGson = new Gson();
        Calendar now = Calendar.getInstance();
        mDate.setText((now.get(Calendar.MONTH) + 1 + "月" + now.get(Calendar.DAY_OF_MONTH) + "日"));
    }


    @OnClick({R.id.tv_right, R.id.mChoosePerson, R.id.mGroupBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.mChoosePerson:
                Intent mChoosePersonIntent = new Intent(this, WebViewActivity.class);
                mChoosePersonIntent.putExtra(Contants.TYPE, 7);
                startActivityForResult(mChoosePersonIntent, 1);
                break;
            case R.id.mGroupBtn:
                if (!StrUtil.isNotEmpty(mEditContent, true)) {
                    ToastUtil.setToast("请输入要发送的内容");
                    return;
                }
                if (TextUtils.isEmpty(ids)) {
                    ToastUtil.setToast("请选择患者");
                    return;
                }

                LoadDialog.show(this);
                Integer DrId = (Integer) SpUtils.get(Contants.Id, 0);
                String DrName = (String) SpUtils.get(Contants.Name, "");
                SendGroupMessageEntity mSendGroupMessageEntity = new SendGroupMessageEntity();
                mSendGroupMessageEntity.setQueryTypeId(2);
                mSendGroupMessageEntity.setQueryText(ids);
                mSendGroupMessageEntity.setDrId(DrId);
                mSendGroupMessageEntity.setDrName(DrName);
                mSendGroupMessageEntity.setContent(mEditContent.getText().toString());
                mSendGroupMessageEntity.setImagePaths(mSavePicList);

                String json = mGson.toJson(mSendGroupMessageEntity);
                RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
                NetServices.Factory.getService().AddFeedBack(
                        body
                ).subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new BaseComPleteObserver(NewlyBuildGroupActivity.this) {
                            @Override
                            protected void onSuccees(BaseEntity t) throws Exception {
                                ToastUtil.setToast("群发消息成功");
                                finish();
                                return;

                            }

                        });
                break;

        }
    }

    // 处理选择的照片的地址
    private void refreshAdapter(List<BaseMedia> picList) {
        mPicList.clear();
        for (BaseMedia localMedia : picList) {
            //被压缩后的图片路径
            String compressPath = localMedia.getPath(); //压缩后的图片路径
            mPicList.add(compressPath); //把图片添加到将要上传的图片数组中
        }

        for (String path : mPicList) {
            uploadPicture(path);
        }
    }

    private void uploadPicture(String path) {
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                compressImage(path, emitter);
            }
        }).subscribe(new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(String s) {
                Log.d(TAG, "onNext" + s);
                uploadImge(s, path);
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void uploadImge(String s, final String path) {

        NetServices.Factory.getService().UploadImage(
                s + ""
                , "3"
        ).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseComPleteObserver<UploadImageEntity>(NewlyBuildGroupActivity.this) {
                    @Override
                    protected void onSuccees(BaseEntity<UploadImageEntity> t) throws Exception {
                        Log.d(TAG, t.getData().toString());
                        mSavePicList.add(t.getData().getSavePath());
                        uploadView.addFile(new File(path));
                    }

                });

    }

    public void compressImage(String filePath, final ObservableEmitter<String> emitter) {
        File oldFile = new File(filePath);
        Log.d("图片压缩", "之前" + oldFile.length());
        Luban.with(NewlyBuildGroupActivity.this)
                .load(filePath)
                .ignoreBy(100)
                .setTargetDir(Environment.getExternalStorageDirectory().getAbsolutePath())
                .filter(new CompressionPredicate() {
                    @Override
                    public boolean apply(String path) {
                        return !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif"));
                    }
                })
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onSuccess(File file) {

                        Log.d("图片压缩", "之后" + file.length());
                        emitter.onNext(Base64Util.imageToBase64(file.getAbsolutePath()));


                    }

                    @Override
                    public void onError(Throwable e) {
                    }
                }).launch();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 1:
                    ids = data.getStringExtra("ids");
                    Log.d("NewlyBuildGroupActivity", "打印数据------" + ids);
                    GroupChoosePersonData mResultData = mGson.fromJson(ids, GroupChoosePersonData.class);
                    ids = mResultData.getData();
                    mPersonContent.setText(mResultData.getName());
                    break;
                case IMAGE_REQUEST_CODE:
                    List<BaseMedia> medias = Boxing.getResult(data);
//                    Uri selectedImage = data.getData(); //获取系统返回的照片的Uri
//                    String[] filePathColumn = {MediaStore.Images.Media.DATA};
//                    Cursor cursor = NewlyBuildGroupActivity.this.getContentResolver().query(selectedImage,
//                            filePathColumn, null, null, null);//从系统表中查询指定Uri对应的照片
//                    cursor.moveToFirst();
//                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
//                    String path = cursor.getString(columnIndex);  //获取照片路径
//                    uploadPicture(path);
                    if (null != medias) {
                        if (medias.size() > 0) {
                            uploadPicture(medias.get(0).getPath());
                        }
                    }
                    break;
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
